package com.lm.jdbcclient.repository;

import com.lm.jdbcclient.entry.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserRepository {

    @Autowired
    private JdbcClient jdbcClient;

    private final RowMapper<SysUserEntity> userRowMapper = (ResultSet rs, int rowNum) -> {
        SysUserEntity user = new SysUserEntity();
        user.setUserId(rs.getLong("user_id"));
        user.setUsername(rs.getString("username"));
        user.setEmail(rs.getString("email"));
        return user;
    };

    public void createUser(String name, String email) {
        jdbcClient.sql("INSERT INTO sys_user (username, email) VALUES (?, ?)")
                .param(name)
                .param(email)
                .update();
    }

    public SysUserEntity getUserById(Long id) {
        return jdbcClient.sql("SELECT * FROM sys_user WHERE user_id = ?")
                .param(id)
                .query(userRowMapper)
                .single();
    }

    public List<SysUserEntity> getAllUsers() {
        return jdbcClient.sql("SELECT * FROM sys_user")
                .query(userRowMapper)
                .list();
    }

    public void updateUser(Long id, String name, String email) {
        jdbcClient.sql("UPDATE sys_user SET username = ?, email = ? WHERE user_id = ?")
                .param(name)
                .param(email)
                .param(id)
                .update();
    }

    public void deleteUser(Long id) {
        jdbcClient.sql("DELETE FROM sys_user WHERE user_id = ?")
                .param(id)
                .update();
    }
}
